package com.ybkj.o2o.zhuanche.common.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.o2o.zhuanche.entity.Passenger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Component
public class PassengerApi {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancer;

//    private static final String SERVER_ADDRESS = "http://192.168.0.203:8299";// 正式用户项目地址
    @Value("${spring.mc_url}")
    private String SERVER_ADDRESS;// 正式用户项目地址

    public static final String API_SERVICE_ID = "mc";
    /**
     * V4查询单个乘客.
     */
    public static final String FIND_BYID_V4 =
            "api/passengers/v4/findById.json?passengerId={passengerId}&appKey={appKey}";

    /**
     * 根据乘客Id查询单个乘客.
     *
     * @param passengerId 客户id
     * @param appKey      系统key
     * @return 一个乘客
     */
    public Passenger findById(Long passengerId, String appKey) {
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("passengerId", String.valueOf(passengerId));
        kv.put("appKey", appKey);
        Passenger passenger = null;
        try {
            String response = restTemplate.getForObject(
                    getRestUri(API_SERVICE_ID, SERVER_ADDRESS) + FIND_BYID_V4, String.class, kv);
            JSONObject jsonObject = JSON.parseObject(response);
            passenger = jsonObject.getObject("data", Passenger.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return passenger;
    }

    /**
     * 拼接用户项目服务器地址.
     *
     * @param serviceId   查询地址的名称
     * @param fallbackUrl 备用地址
     * @return 服务器地址
     */

    public String getRestUri(String serviceId, String fallbackUrl) {
        URI uri;
        try {
            ServiceInstance serviceInstance = loadBalancer.choose(serviceId);
            uri = serviceInstance.getUri();
        } catch (RuntimeException ex) {
            //ex.printStackTrace();
            uri = URI.create(fallbackUrl);
        }

        String http = uri.toString();
        if (!http.endsWith("/")) {
            return http + "/";
        }
        return http;
    }
}
